<template>
    <div class="add">
        <el-form
            :model="ruleForm"
            :rules="rules"
            ref="ruleForm"
            label-width="130px"
            hide-required-asterisk
            class="demo-ruleForm"
        >
            <el-form-item label="类型" prop="type">
                <el-radio-group v-model="ruleForm.type">
                    <el-radio
                        v-for="item in reOptions"
                        :key="item.id"
                        :label="item.id"
                        >{{ item.label }}</el-radio
                    >
                </el-radio-group>
            </el-form-item>

            <template v-if="ruleForm.type == 'jyzx'">
                <el-form-item label="交易中心名称" prop="name" :rules="newRule('交易中心名称','required','min2','max20')">
                    <el-input
                        type="text"
                        v-model.trim="ruleForm.name"
                        maxlength="20"
                        show-word-limit
                        clearable=""
                        placeholder="请输入交易中心名称"
                    ></el-input>
                </el-form-item>

                <el-form-item label="地址" prop="address" :rules="newRule('地址','required','min5','max100')">
                    <el-input
                        type="text"
                        v-model.trim="ruleForm.address"
                        maxlength="50"
                        show-word-limit
                        clearable=""
                        placeholder="请输入地址"
                    ></el-input>
                </el-form-item>

                <el-form-item
                    class="phones"
                    v-for="(phone, index) in ruleForm.phones"
                    :label="`${index == 0 ? '联系电话' : ''}`"
                    :key="phone.key"
                    :prop="'phones.' + index + '.value'"
                    :rules="newRule('联系电话','required','phone')"
                >
                    <el-input v-model.trim="phone.value" clearable></el-input>

                    <el-button type="text" icon="el-icon-circle-plus-outline" v-if="index == ruleForm.phones.length-1" @click.prevent="addEmail"></el-button>
                    <el-button type="text" icon="el-icon-remove-outline" v-if="index != 0" @click.prevent="removeEmail(phone)"></el-button>
                </el-form-item>

                <el-form-item key="url1" label="官方网址" prop="gfurl">
                    <el-input
                        type="text"
                        v-model.trim="ruleForm.gfurl"
                        maxlength="100"
                        show-word-limit
                        clearable=""
                        placeholder="输入官方地址"
                    ></el-input>
                </el-form-item>

                <el-form-item key="guide" label="办事指南">
                    <el-input
                        type="textarea"
                        v-model.trim="ruleForm.guide"
                        maxlength="500"
                        show-word-limit
                        clearable=""
                        placeholder="请输入办事指南（选填项）"
                    ></el-input>
                </el-form-item>

                <el-form-item key="notice" label="通知公告">
                    <el-input
                        type="textarea"
                        v-model.trim="ruleForm.notice"
                        maxlength="500"
                        show-word-limit
                        clearable=""
                        placeholder="请输入通知公告（选填项）"
                    ></el-input>
                </el-form-item>
            </template>

            <template v-if="ruleForm.type != 'jyzx'">
                <el-form-item key="name" label="链接名称" prop="name" :rules="newRule('链接名称','required','min2','max20')">
                    <el-input
                        type="text"
                        v-model.trim="ruleForm.name"
                        maxlength="20"
                        show-word-limit
                        clearable=""
                        placeholder="请输入链接名称"
                    ></el-input>
                </el-form-item>

                <el-form-item key="url2" label="链接地址" prop="url">
                    <el-input
                        type="text"
                        v-model.trim="ruleForm.url"
                        maxlength="100"
                        show-word-limit
                        clearable=""
                        placeholder="请输入链接地址"
                    ></el-input>
                </el-form-item>

                <el-form-item key="recommend" label="推荐理由">
                    <el-input
                        type="textarea"
                        v-model.trim="ruleForm.recommend"
                        maxlength="500"
                        show-word-limit
                        clearable=""
                        placeholder="请输入该链接好用的地方（选填项）"
                    ></el-input>
                </el-form-item>
            </template>
            

            <el-form-item label="提出者">
                <el-radio v-model="radio" label="1">{{nickname}}</el-radio>
            </el-form-item>


            <div class="whtie"></div>


            <div class="btns">
                <el-button @click="cancel()" size="medium">取消</el-button>
                <el-button class="btn-submit" type="primary" size="medium" @click="submitForm('ruleForm')"
                    >提交</el-button
                >
            </div>
        </el-form>
    </div>
</template>

<script>
import { mapGetters } from 'vuex';
export default {
    head: {},
    props: {
        types: {
            type: Array,
            default: () => [],
        },
    },
    components: {},
    data() {
        var checkLink = (rule, value, callback) => {
            var len = value.length,
                max = 100,
                min = 5;
            var isUrl = function(url){
                return /^(https?:\/\/(([a-zA-Z0-9]+-?)+[a-zA-Z0-9]+\.)+[a-zA-Z]+)(:\d+)?(\/.*)?(\?.*)?(#.*)?$/.test(url);
            }

            if (!value) {
                return callback(new Error("请输入链接地址"));
            }
            if(len < min || len > max){
                return callback(new Error(`长度在 ${min} 到 ${max} 个字符`));
            }
            if(!isUrl(value)){
                return callback(new Error("请输入正确的链接地址"));
            } else {
                callback();
            }
        };

        var gfCheckLink = (rule, value, callback) => {
            var len = value.length,
                max = 100,
                min = 5;
            var isUrl = function(url){
                return /^(https?:\/\/(([a-zA-Z0-9]+-?)+[a-zA-Z0-9]+\.)+[a-zA-Z]+)(:\d+)?(\/.*)?(\?.*)?(#.*)?$/.test(url);
            }

            if (!value) {
                return callback(new Error("请输入官方网址"));
            }
            if(len < min || len > max){
                return callback(new Error(`长度在 ${min} 到 ${max} 个字符`));
            }
            if(!isUrl(value)){
                return callback(new Error("请输入正确的官方网址"));
            } else {
                callback();
            }
        };

        return {
            radio:'1',
            ruleForm: {
                name: "",
                address:"",
                phones: [
                    {
                        value: "",
                    }
                ],
                url:"",
                gfurl:"",
                guide:"",
                notice:"",
                type: "jyzx",
                recommend:"",
                mobile:""
            },
            rules: {
                type: [
                    {
                        required: true,
                        message: "请选择类型",
                        trigger: "change",
                    },
                    
                ],
                url: [
                    {validator: checkLink, trigger: 'blur'}
                ],
                gfurl: [
                    {validator: gfCheckLink, trigger: 'blur'}
                ],
            },
            options: [
                {
                    id: "jyzx",
                    label: "交易中心及办事指南",
                },
                {
                    id: "jypt",
                    label: "交易平台",
                },
                {
                    id: "gjxz",
                    label: "工具下载",
                },
                {
                    id: "qtfw",
                    label: "其他服务",
                },
            ],
        };
    },
    computed: {
        // 根据types展示可选择的类型
        reOptions() {
            return this.options.filter(item => {
                return ~this.types.indexOf(item.id);
            });
        },
        ...mapGetters({
            userinfo: 'userinfo/getData',
            nickname: 'userinfo/getNickname',
        }),
    },
    methods: {
        submitForm(formName) {
            const that  = this;
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    let obj = clone(that.ruleForm);

                    obj.mobile = obj.phones.map(item =>item.value).toString();

                    obj.url = obj.type == 'jyzx' ? obj.gfurl : obj.url;

                    that.$ajax({
                        type: "post",
                        url: `${that.$store.state.api.tbUrl}/home/addnavigate.json`,
                        data: obj,
                        callback: function (data,res) {
                            ShowMsg( '提交成功，谢谢您的反馈，我们会尽快核实并添加，核实且添加后，我们也会赠送您XX奖励！', 'success');
                            that.cancel();
                        },
                        error: function () {},
                    });
                } else {
                    console.log("error submit!!");
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        },
        cancel(){
            this.$emit('cancel')
        },
        addEmail() {
            this.ruleForm.phones.push({
                value: "",
                key: Date.now(),
            });
        },
        removeEmail(item) {
            var index = this.ruleForm.phones.indexOf(item);
            if (index !== -1) {
                this.ruleForm.phones.splice(index, 1);
            }
        },
    },
    mounted() {},
    beforeDestroy() {},
};
</script>

<style lang="scss" scoped>
@import "@css/var.scss";
.add {
    width: 90%;
    position: relative;

    ::v-deep .el-input--suffix .el-input__inner{
        padding-right: 75px;
    }

    .phones {
        .el-input {
            width: 80%;
        }
        .el-button {
            font-size: 20px;
        }
    }

    .whtie {
        height: 20px;
    }

    .btns {
        position: absolute;
        bottom: 0px;
        right: 0;

        .btn-submit {
            width: 90px;
        }
    }
}
</style>
 